package com.hwbsite.hwbback.service;

import cn.hutool.core.io.IoUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.hwbsite.hwbback.config.MinioTemplate;
import com.hwbsite.hwbback.config.OssNoTokenBucket;
import com.hwbsite.hwbback.consstants.CacheConstants;
import com.hwbsite.hwbback.consstants.CommonConstants;
import com.hwbsite.hwbback.entity.MEmoji;
import com.hwbsite.hwbback.entity.UserInfo;
import com.hwbsite.hwbback.mapper.MEmojiMapper;
import com.hwbsite.hwbback.utils.TokenRes;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
@AllArgsConstructor
public class CommonServiceImpl implements CommonService{

    private final MEmojiMapper mEmojiMapper;
    private final MinioTemplate minioTemplate;
    private final OssNoTokenBucket ossNoTokenBucket;
    private final RedisTemplate redisTemplate15;

    @Override
    public List<MEmoji> getEmoji() {
        return mEmojiMapper.selectList(Wrappers.<MEmoji>lambdaQuery().orderByAsc(MEmoji::getOrderNo));
    }

    @Override
    public byte[] getFile(String path) {
        try{
            List<String> filePath = Arrays.stream(path.split("-",2)).collect(Collectors.toList());
            String bucket = filePath.get(0);
            String fileName = filePath.get(1);
            return IoUtil.readBytes(minioTemplate.fileDowner(bucket, fileName));
        }catch (Exception e){
            log.error("下载异常",e);
            return null;
        }
    }

    @Override
    public byte[] geNotFile(String path) {
       if(ossNoTokenBucket.getBucket().stream().anyMatch(e->path.contains(e))){

            return getFile(path);
       }

        return null;
    }

    @Override
    public boolean isTokenValid(String token) {

        return redisTemplate15.hasKey(CacheConstants.USER_TOKEN + token);
    }

    @Override
    public void logOut(UserInfo userInfo) {
        if(redisTemplate15.hasKey(CacheConstants.USER_TOKEN_ED + userInfo.getUserId())) {

            String tokens =  (String) redisTemplate15.opsForValue().get(CacheConstants.USER_TOKEN_ED + userInfo.getUserId());

            TokenRes res =  JSONUtil.toBean(tokens, TokenRes.class);

            if (redisTemplate15.hasKey(CacheConstants.USER_TOKEN + res.getAccess_token())) {
                redisTemplate15.delete(CacheConstants.USER_TOKEN + res.getAccess_token());
            }
            if (redisTemplate15.hasKey(CacheConstants.RE_USER_TOKEN + res.getAccess_token())) {
                redisTemplate15.delete(CacheConstants.RE_USER_TOKEN + res.getAccess_token());
            }

            redisTemplate15.delete(CacheConstants.USER_TOKEN_ED + userInfo.getUserId());
        }
    }
}
